<template>
  <el-dialog
    v-el-drag-dialog
    :title="title"
    :visible.sync="visible"
    width="1200px"
    @closed="reset"
  >
    <div>
      <div class="top-name">
        <span class="label">权益名称：</span><el-input v-model="preferentialPackageName" :disabled="curType === 'detail' || curType === 'record'" style="width: 400px;" />
      </div>
      <div>
        <el-button v-if="curType === 'add' || curType === 'edit'" class="add-btn" type="primary" @click="addRow">添加</el-button>
        <el-table :data="tableData" style="width: 100%;">
          <el-table-column prop="gtId" label="商品分类" width="120">
            <template slot-scope="scope">
              <el-select v-if="scope.row.edit" v-model="scope.row.gtId" size="mini" style="width: 100px;" placeholder="请选择">
                <el-option
                  v-for="item in gtList"
                  :key="item.gtId"
                  :label="item.gtName"
                  :value="item.gtId"
                />
              </el-select>
              <span v-else>{{ scope.row.gtName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="goodsId" label="商品名称" width="120">
            <template slot-scope="scope">
              <el-select v-if="scope.row.edit" v-model="scope.row.goodsId" size="mini" style="width: 100px;" placeholder="请选择" @change="goodChange(scope.$index, scope.row.goodsId)">
                <el-option
                  v-for="item in gtList[0].goodsList"
                  :key="item.goodsId"
                  :label="item.goodsName"
                  :value="item.goodsId"
                />
              </el-select>
              <span v-else>{{ scope.row.goodsName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="specName" label="规格型号" width="80" />
          <el-table-column prop="disType" label="调整类型" width="120">
            <template slot-scope="scope">
              <el-select v-if="scope.row.edit" v-model="scope.row.disType" size="mini" style="width: 100px;" placeholder="请选择" @change="(value) =>changeDisType(value,scope.row)">
                <el-option
                  v-for="item in disTypeMap"
                  :key="item.value"
                  :label="item.desc"
                  :value="item.value"
                />
              </el-select>
              <span v-else>{{ scope.row.disType && formatColumnMap(disTypeMap, 'value', scope.row.disType, 'desc') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="disCount" label="调整数值" width="120">
            <template slot-scope="scope">
              <el-input-number v-if="scope.row.edit" v-model="scope.row.disCount" size="mini" :controls="false" :min="0" :max="99999" :precision="2" style="width: 100px;" @change="disCountChange(scope.$index, scope.row.disCount)" />
              <span v-else>{{ scope.row.disCount }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="price1" label="挂牌价(￥)" width="90" />
          <el-table-column prop="price2" label="优惠价(￥)" width="90">
            <template slot-scope="scope">
              <span>{{ scope.row.price2.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="disLimit" label="优惠上限" width="120">
            <template slot-scope="scope">
              <el-input-number v-if="scope.row.edit" v-model="scope.row.disLimit" size="mini" :controls="false" :min="0" :precision="2" :max="99999" style="width: 100px;" />
              <span v-else>{{ scope.row.disLimit }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="timeLimit" label="优惠时限" width="120">
            <template slot-scope="scope">
              <el-select v-if="scope.row.edit" v-model="scope.row.timeLimit" size="mini" style="width: 100px;" placeholder="请选择">
                <el-option
                  v-for="item in timeLimitTypeMap"
                  :key="item.value"
                  :label="item.desc"
                  :value="item.value"
                />
              </el-select>
              <span v-else>{{ scope.row.timeLimit && formatColumnMap(timeLimitTypeMap, 'value', scope.row.timeLimit, 'desc') }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="curType === 'add' || curType === 'edit'" label="操作" fixed="right" width="130">
            <template slot-scope="scope">
              <el-link v-if="scope.row.edit" :underline="false" size="mini" @click="scope.row.edit = !scope.row.edit">结束编辑</el-link>
              <el-link v-else :underline="false" size="mini" @click="scope.row.edit = !scope.row.edit">编辑</el-link>
              <el-link :underline="false" size="mini" @click="handleDelete(scope.$index)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        <div class="title"><i class="el-icon-s-cooperation icon-title" />通用渠道</div>
        <el-checkbox-group v-model="checkList">
          <el-checkbox label="微信公众号" :disabled="curType === 'detail' || curType === 'record'" />
          <el-checkbox label="呼叫中心" :disabled="curType === 'detail' || curType === 'record'" />
          <el-checkbox label="门店" :disabled="curType === 'detail' || curType === 'record'" />
          <el-checkbox label="支付宝小程序" :disabled="curType === 'detail' || curType === 'record'" />
          <el-checkbox label="话务下单" :disabled="curType === 'detail' || curType === 'record'" />
          <el-checkbox label="教客下单" :disabled="curType === 'detail' || curType === 'record'" />
        </el-checkbox-group>
      </div>
    </div>
    <div v-if="curType === 'add' || curType === 'edit'" slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button type="primary" @click="handleSave">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { preferentialDetailLast, preferentialDetail, priceBase, preferentialAdd, preferentialEdit } from '@/api'
  import { formatColumnMap } from '@/utils'
  // import { Decimal } from 'decimal.js'
  export default {
    name: 'addLegal',
    data() {
      return {
        title: '',
        visible: false,
        curType: '',
        preferentialPackageName: '',
        tableData: [],
        gtList: [],
        disTypeMap: [],
        timeLimitTypeMap: [],
        checkList: []
      }
    },

    async created() {
    },
    mounted() {

    },
    methods: {
      formatColumnMap,
      async open(temp) {
        this.curType = temp.type
        this.temp = temp
        this.tableData = []
        this.preferentialPackageName = ''
        this.checkList = []
        this.visible = true
        if (this.curType === 'add') {
          this.title = '优惠权益设定'
          this.checkList = ['微信公众号', '呼叫中心', '门店', '支付宝小程序', '话务下单']
        } else if (this.curType === 'edit') {
          this.title = '优惠设定'
        } else {
          this.title = '优惠权益详情'
        }
        this.preferentialDetail()
        if (this.curType === 'record') {
          this.preferentialLast()
        }
      },
      // 获取详情
      async preferentialDetail() {
        const params = {
          preferentialPackageId: '',
          detail: 0
        }
        if (this.curType === 'edit') {
          params.preferentialPackageId = this.temp.preferentialPackageId
        }
        if (this.curType === 'detail') {
          params.preferentialPackageId = this.temp.preferentialPackageId
          params.detail = 1
        }
        const res = await preferentialDetail(params)
        this.disTypeMap = JSON.parse(res.data.disTypeMap)
        this.gtList = JSON.parse(res.data.gtList)
        this.gtList[0].goodsList = this.gtList[0].goodsList.filter(item => item.pricingMode === 1)
        this.preferentialPackageInfo = JSON.parse(res.data.preferentialPackageInfo)
        this.timeLimitTypeMap = JSON.parse(res.data.timeLimitTypeMap)
        this.preferentialPackageName = this.preferentialPackageInfo.preferentialPackageName
        if (this.preferentialPackageInfo.detailInfoList) {
          this.tableData = this.preferentialPackageInfo.detailInfoList
        } else {
          this.tableData = []
        }
        if (this.tableData.length > 0) {
          this.tableData.forEach((item, index) => {
            this.$set(this.tableData[index], 'edit', false)
            item.disCount = item.disCount / 100
          })
        }
        if ((this.preferentialPackageInfo.platOptions & 1) > 0) {
          this.checkList.push('呼叫中心')
        }
        if ((this.preferentialPackageInfo.platOptions & 1 << 1) > 0) {
          this.checkList.push('微信公众号')
        }
        if ((this.preferentialPackageInfo.platOptions & 1 << 3) > 0) {
          this.checkList.push('门店')
        }
        if ((this.preferentialPackageInfo.platOptions & 1 << 5) > 0) {
          this.checkList.push('支付宝小程序')
        }
        if ((this.preferentialPackageInfo.platOptions & 1 << 6) > 0) {
          this.checkList.push('话务下单')
        }
        if ((this.preferentialPackageInfo.platOptions & 1 << 2) > 0) {
          this.checkList.push('教客下单')
        }
        console.log(this.disTypeMap)
        console.log(this.gtList)
        console.log(this.preferentialPackageInfo)
        console.log(this.timeLimitTypeMap)
      },
      // 获取上次调整记录
      async preferentialLast() {
        const res = await preferentialDetailLast({ preferentialPackageId: this.temp.preferentialPackageId, detail: 1 })
        if (res.data) {
          this.disTypeMap = JSON.parse(res.data.disTypeMap)
          this.gtList = JSON.parse(res.data.gtList)
          this.preferentialPackageInfo = JSON.parse(res.data.preferentialPackageInfo)
          this.timeLimitTypeMap = JSON.parse(res.data.timeLimitTypeMap)
          this.preferentialPackageName = this.preferentialPackageInfo.preferentialPackageName
          this.tableData = this.preferentialPackageInfo.detailInfoList
          if (this.tableData.length > 0) {
            this.tableData.forEach((item) => {
              item.disCount = item.disCount / 100
            })
          }
          if ((this.preferentialPackageInfo.platOptions & 1) > 0) {
            this.checkList.push('呼叫中心')
          }
          if ((this.preferentialPackageInfo.platOptions & 1 << 1) > 0) {
            this.checkList.push('微信公众号')
          }
          if ((this.preferentialPackageInfo.platOptions & 1 << 3) > 0) {
            this.checkList.push('门店')
          }
          if ((this.preferentialPackageInfo.platOptions & 1 << 5) > 0) {
            this.checkList.push('支付宝小程序')
          }
          if ((this.preferentialPackageInfo.platOptions & 1 << 6) > 0) {
            this.checkList.push('话务下单')
          }
          if ((this.preferentialPackageInfo.platOptions & 1 << 2) > 0) {
            this.checkList.push('教客下单')
          }
        }
      },
      addRow() {
        const row = {}
        row.gtId = this.gtList[0].gtId // 商品分类
        row.gtName = this.gtList[0].gtName
        row.goodsId = '' // 商品名称
        row.goodsName = ''
        row.specCode = '' // 规格型号
        row.specName = ''
        row.disType = 1 // 调整类型
        row.disCount = 0 // 调整数值
        row.price1 = '' // 挂牌价
        row.price2 = 0.00 // 优惠价
        row.disLimit = ''
        row.timeLimit = ''
        row.edit = true
        this.tableData.push(row)
      },
      async goodChange(index, value) {
        const goods = this.gtList[0].goodsList.find(item => item.goodsId === value)
        console.log(goods)
        this.tableData[index].goodsName = goods.goodsName
        this.tableData[index].specCode = goods.specCode
        this.tableData[index].specId = goods.specId
        this.tableData[index].specName = goods.specName
        const res = await priceBase({ goodsId: goods.goodsId })
        var goodsInfo = {}
        for (var i in res.data) {
          var data = res.data[i]
          if (data.areaPriceType === 1 && data.fromPlat === 1) {
            goodsInfo = data
          }
        }
        if (!goodsInfo.price0) {
          this.$message.warning('当前商品不存在挂牌价')
          return
        }
        this.tableData[index].price1 = goodsInfo.price0
      },
      disCountChange(index, value) {
        if (!this.tableData[index].price1) {
          this.$message.warning('请选择商品')
          this.$nextTick(() => {
            this.tableData[index].disCount = 0.00
          })
          return
        }
        if (this.tableData[index].disType === 1) {
          if (value > this.tableData[index].price1) {
            this.$message.warning('调整数值不能大于挂牌价格')
            return
          }
          this.tableData[index].price2 = this.tableData[index].price1 - this.tableData[index].disCount
        }

        if (this.tableData[index].disType === 2) {
          if (value > 1 || value < 0) {
            this.$message.warning('调整数值需要在0-1之间')
            return
          }
          this.tableData[index].price2 = this.tableData[index].price1 * this.tableData[index].disCount
        }
        if (this.tableData[index].disType === 3) {
          if (value < 0) {
            this.$message.warning('调整数值不能小于0')
            return
          }
          this.tableData[index].price2 = this.tableData[index].disCount
        }
        if (this.tableData[index].disType === 4) {
          if (value < 0) {
            this.$message.warning('调整数值不能小于0')
            return
          }
          this.tableData[index].price2 = this.tableData[index].price1 + this.tableData[index].disCount
        }
      },
      handleDelete(index) {
        this.tableData.splice(index, 1)
      },
      handleSave() {
        if (!this.preferentialPackageName) {
          this.$message.warning('请输入权益名称')
          return
        }
        if (this.checkList.length === 0) {
          this.$message.warning('请选择适用渠道')
          return
        }
        const paramInfo = {
          preferentialPackageName: this.preferentialPackageName
        }
        paramInfo.platOptions = 0
        if (this.checkList.indexOf('微信公众号') > -1) {
          paramInfo.platOptions |= 1 << 1
        }
        if (this.checkList.indexOf('呼叫中心') > -1) {
          paramInfo.platOptions |= 1
        }
        if (this.checkList.indexOf('门店') > -1) {
          paramInfo.platOptions |= 1 << 3
        }
        if (this.checkList.indexOf('支付宝小程序') > -1) {
          paramInfo.platOptions |= 1 << 5
        }
        if (this.checkList.indexOf('话务下单') > -1) {
          paramInfo.platOptions |= 1 << 6
        }
        if (this.checkList.indexOf('教客下单') > -1) {
          paramInfo.platOptions |= 1 << 2
        }
        if (this.tableData.length > 0) {
          for (var x = 0; x < this.tableData.length; x++) {
            var row = this.tableData[x]
            var disType = row.disType
            if (!row.goodsName) {
              this.$message.warning('请选择商品名称')
              return
            }
            row.disType = Number(row.disType)
            if (!row.disType) {
              this.$message.warning('请选择' + row.goodsName + '的优惠类型')
              return
            }
            var disCount = row.disCount
            if (disType === 2 && disCount > 1) {
              this.$message.warning('商品:' + row.goodsName + '调整数值输入有误')
              return
            }
            if (!disCount) {
              this.$message.warning('商品:' + row.goodsName + '调整数值输入有误')
              return
            }
            if (disType === 1) {
              if (disCount < 0) {
                this.$message.warning('调整数值不能为负数！')
                return
              }
              var price1 = row.price1
              var price2Value = price1 - disCount
              if (price2Value < 0) {
                this.$message.warning('调整数值不能大于挂牌价！')
                return
              }
            }
            row.disLimit = Number(row.disLimit)
            if (!row.disLimit) {
              this.$message.warning('请输入' + row.goodsName + '的优惠上限')
              return
            }
            row.timeLimit = Number(row.timeLimit)
            if (!row.timeLimit) {
              this.$message.warning('请选择' + row.goodsName + '的优惠时限')
              return
            }
            row.disCount = Number(row.disCount) * 100
          }
        }
        paramInfo.detailInfoList = this.tableData
        if (this.curType === 'add') {
          preferentialAdd(paramInfo).then(res => {
            if (res.data) {
              this.$message.success('保存成功')
              this.visible = false
              this.$emit('refresh')
            }
          })
        }
        if (this.curType === 'edit') {
          paramInfo.preferentialPackageId = this.temp.preferentialPackageId
          preferentialEdit(paramInfo).then(res => {
            if (res.data) {
              this.$message.success('保存成功')
              this.visible = false
              this.$emit('refresh')
            }
          })
        }
      },
      changeDisType(value, row) {
        if (value === 1) {
          if (row.price1 < row.disCount) {
            this.$message.warning('调整数值不能大于挂牌价格')
            return
          }
          row.price2 = row.price1 - row.disCount
        }
        if (value === 2) {
          console.log(row.disCount)
          if (row.disCount < 0 || row.disCount > 1) {
            this.$message.warning('调整数值需要在0-1之间')
            return
          }
          row.price2 = row.price1 * row.disCount
        }
        if (value === 3) {
          if (row.disCount < 0) {
            this.$message.warning('调整数值不能小于0')
            return
          }
          row.price2 = row.disCount
        }
        if (value === 4) {
          if (row.disCount < 0) {
            this.$message.warning('调整数值不能小于0')
            return
          }
          row.price2 = row.price1 + row.disCount
        }
      },
      reset() {

      }
    }
  }
</script>

<style lang="scss" scoped>
  .top-name {
    display: flex;
    margin-bottom: 10px;
    .label {
      width: 90px;
      line-height: 30px;
    }
  }
  .add-btn {
    margin-bottom: 10px;
  }
  .title {
    margin: 20px 0 10px 0;
    font-weight: 700;
    .icon-title {
      margin-right: 5px;
    }
  }
</style>
